package com.hundsun.cprs.yyt.service.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.broker.gateway.response.UserReferRelateResponse;
import com.hundsun.cprs.broker.gateway.response.UserUpReferRelateResponse;
import com.hundsun.cprs.broker.gateway.service.RemoteUserRelateService;
import com.hundsun.cprs.broker.gateway.vo.ReferRelateRequestVo;
import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.broker.dao.BrokerCommisionFlowDao;
import com.hundsun.cprs.yyt.service.broker.domain.BrokerCommisionFlow;
import com.hundsun.cprs.yyt.service.broker.enums.EnumBrokerCommisionFlowStatus;
import com.hundsun.cprs.yyt.service.common.dto.BrokerReferRelateInfo;
import com.hundsun.cprs.yyt.service.common.dto.ReferRelateInfo;
import com.hundsun.cprs.yyt.service.common.dto.ReferRelateRequestDto;
import com.hundsun.cprs.yyt.service.common.dto.UserReferRelateDto;
import com.hundsun.cprs.yyt.service.common.service.RemoteBrokerService;
import com.hundsun.cprs.yyt.service.dilivery.domain.DiliveryAddress;
import com.hundsun.cprs.yyt.service.dilivery.service.DiliveryAddressService;
import com.hundsun.cprs.yyt.service.order.dto.OrderInfo;
import com.hundsun.cprs.yyt.service.order.service.OrderService;
import com.hundsun.cprs.yyt.service.rabbit.RoutingKeyConstants;
import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.domain.TradeMatchDetail;
import com.hundsun.cprs.yyt.service.trade.dto.TradeCounterpartyInfo;
import com.hundsun.cprs.yyt.service.trade.enums.EnumEntustBSType;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustService;
import com.hundsun.cprs.yyt.service.trade.service.TradeMatchService;
import com.hundsun.cprs.yyt.util.BeanUtils;
import com.hundsun.cprs.yyt.util.DateUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.*;

@Service
public class RemoteBrokerServiceImpl extends BaseService implements RemoteBrokerService {

    @Autowired(required=false)
    private RemoteUserRelateService remoteUserRelateService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private DiliveryAddressService diliveryAddressService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private TradeMatchService tradeMatchService;

    @Autowired
    private BrokerCommisionFlowDao brokerCommisionFlowDao;

    @Autowired
    private TradeEntrustService tradeEntrustService;

    @Override
    public void tradeSplitCommission(Long entrustId) {

        TradeEntrust tradeEntrust = tradeEntrustService.getTradeEntrustById(entrustId);
        if (tradeEntrust == null){
            throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1520.getErrorNo(),EnumBusinessCode.BUSINESS_1520.getErrorInfo());
        }
        //获取委托单对应的订单详情
        OrderInfo orderInfo = orderService.selectOrderInfoByOrderSn(tradeEntrust.getOrderSn());
        if (orderInfo == null){
            throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1501.getErrorNo(),EnumBusinessCode.BUSINESS_1501.getErrorInfo());
        }
        try{
            //对接佣金宝数据拼接
            String transDate = DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss.S",tradeEntrust.getEntrustTime());
            //获取提货地址详情
            DiliveryAddress diliveryAddress = diliveryAddressService.selectAddressDetailByAddressId(orderInfo.getDiliveryId());
            if (diliveryAddress == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1903.getErrorNo(),EnumBusinessCode.BUSINESS_1903.getErrorInfo());
            }
            //获取到买方的交易对手方信息（匹配单详情）
            List<TradeMatchDetail> tradeMatchDetailList = tradeMatchService.selectCounterpartyTradeMatchDetailList(tradeEntrust.getId(),EnumEntustBSType.SELL.getCode().toString());
            List<TradeCounterpartyInfo> tradeCounterpartyList = new ArrayList<>();
            if (!tradeMatchDetailList.isEmpty()){
                for (TradeMatchDetail tradeMatchDetail:tradeMatchDetailList){
                    TradeCounterpartyInfo tradeCounterpartyInfo = new TradeCounterpartyInfo();
                    tradeCounterpartyInfo.setUserId(tradeMatchDetail.getEntrust().getUserId());
                    tradeCounterpartyInfo.setFundAccount(tradeMatchDetail.getEntrust().getFundAccount());
                    tradeCounterpartyInfo.setMatchFund(tradeMatchDetail.getMatchFundAmount());
                    tradeCounterpartyList.add(tradeCounterpartyInfo);
                }
            }else{
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1122.getErrorNo(),EnumBusinessCode.BUSINESS_1122.getErrorInfo());
            }
            Map<String,Object> commissionMap = new HashMap<>();
            commissionMap.put("userId",tradeEntrust.getUserId());
            commissionMap.put("fundAccount",tradeEntrust.getFundAccount());
            commissionMap.put("matchId",tradeEntrust.getEntrustNo());
            commissionMap.put("matchAmount",tradeEntrust.getEntrustAmount());
            commissionMap.put("promiseCommission",Math.abs(tradeEntrust.getBusinessFund()));
            commissionMap.put("matchFund",Math.abs(tradeEntrust.getBusinessFund()));
            commissionMap.put("matchCommission",Math.abs(tradeEntrust.getBusinessFund()));
            commissionMap.put("goodsTranseDate",transDate);
            commissionMap.put("goodsName",orderInfo.getOrderItems().get(0).getGoodsName());
            commissionMap.put("goodsCode",tradeEntrust.getGoodsCode());
            commissionMap.put("goodsId",tradeEntrust.getGoodsId());
            commissionMap.put("diliveryAddr",diliveryAddress.getDiliveryAddress());
            commissionMap.put("provinceCode",diliveryAddress.getProvinceCode());
            commissionMap.put("cityCode",diliveryAddress.getMunicipalCode());
            commissionMap.put("countyCode",diliveryAddress.getCountyCode());
            commissionMap.put("dataType","trade");
            commissionMap.put("fundDisburseUserJson",JSON.toJSONString(tradeCounterpartyList));
            try {
                //通知佣金宝处理分佣数据
                rabbitTemplate.convertAndSend(RoutingKeyConstants.YYT_BROKER_COMMISION_COMMIT, commissionMap);
                //生成分佣成功流水
                createCommissionFlow(commissionMap, EnumBrokerCommisionFlowStatus.SUCCESS.getCode());
            }catch (Exception e){
                //生成分佣失败流水
                createCommissionFlow(commissionMap,EnumBrokerCommisionFlowStatus.FAIL.getCode());
            }
        }catch (Exception e){
            logger.error(MessageFormat.format("对接佣金宝，分拥数据传递处理失败[{0}/{1}/{2}],异常:",orderInfo.getUserId(),orderInfo.getUserName(),tradeEntrust.getEntrustNo()),e);
        }
    }

    @Override
    public BrokerReferRelateInfo queryBrokerRelateList(ReferRelateRequestDto request) {
        BrokerReferRelateInfo brokerReferRelateInfo = new BrokerReferRelateInfo();
        ReferRelateRequestVo requestVo = BeanUtils.transfrom(ReferRelateRequestVo.class,request);
        UserReferRelateResponse referRelateResponse = remoteUserRelateService.getReferRelate(requestVo);
        if (!referRelateResponse.isSuccess()){
            throw new ServiceCodeException(referRelateResponse.getErrorNo(),referRelateResponse.getErrorDesc());
        }else{
            brokerReferRelateInfo = BeanUtils.transfrom(BrokerReferRelateInfo.class,referRelateResponse);
            brokerReferRelateInfo.setUserReferRelateDtoList(BeanUtils.batchTransform(UserReferRelateDto.class,referRelateResponse.getUserReferRelates()));
        }
        return brokerReferRelateInfo;
    }

    /**
     * 获取上属推荐人信息
     * @return
     */
    public ReferRelateInfo queryReferRelate(String userId){
        ReferRelateInfo referRelateInfo = new ReferRelateInfo();

        //获取用户上属信息
        UserUpReferRelateResponse userUpReferRelateResponse = remoteUserRelateService.getUpRelate(userId,null);
        if (!userUpReferRelateResponse.isSuccess()){
            throw new ServiceCodeException(userUpReferRelateResponse.getErrorNo(),userUpReferRelateResponse.getErrorDesc());
        }else{
            referRelateInfo = BeanUtils.transfrom(ReferRelateInfo.class,userUpReferRelateResponse);
        }

        return referRelateInfo;
    }


    protected void createCommissionFlow(Map<String,Object> commissionMap,String status){
        BrokerCommisionFlow brokerCommisionFlow = new BrokerCommisionFlow();
        brokerCommisionFlow.setCitycode(commissionMap.get("cityCode").toString());
        brokerCommisionFlow.setCountycode(commissionMap.get("countyCode").toString());
        brokerCommisionFlow.setDatatype(commissionMap.get("dataType").toString());
        brokerCommisionFlow.setDiliveryaddr(commissionMap.get("diliveryAddr").toString());
        brokerCommisionFlow.setFundaccount(commissionMap.get("fundAccount").toString());
        brokerCommisionFlow.setFunddisburseuserjson(commissionMap.get("fundDisburseUserJson").toString());
        brokerCommisionFlow.setGoodscode(commissionMap.get("goodsCode").toString());
        brokerCommisionFlow.setGoodsid((Long) commissionMap.get("goodsId"));
        brokerCommisionFlow.setGoodsname(commissionMap.get("goodsName").toString());
        brokerCommisionFlow.setGoodstransedate(commissionMap.get("goodsTranseDate").toString());
        brokerCommisionFlow.setMatchamount((Long) commissionMap.get("matchAmount"));
        brokerCommisionFlow.setMatchcommission((Long) commissionMap.get("matchCommission"));
        brokerCommisionFlow.setMatchfund((Long) commissionMap.get("matchFund"));
        brokerCommisionFlow.setMatchid(commissionMap.get("matchId").toString());
        brokerCommisionFlow.setPromisecommission((Long) commissionMap.get("promiseCommission"));
        brokerCommisionFlow.setProvincecode(commissionMap.get("provinceCode").toString());
        brokerCommisionFlow.setStatus(status);
        brokerCommisionFlow.setUserId((Long) commissionMap.get("userId"));
        brokerCommisionFlowDao.insert(brokerCommisionFlow);
    }
}
